package com.shanzhi.connection.common;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Slf4j
public class ConnectionUtils {

    /**
     * 内部封装的通用发送方法
     *
     * @param jsonStr          JSON 请求体（用于POST和PUT）
     * @param url              请求地址
     * @param headerCustomizer 自定义 header 的操作
     * @param requestType      请求类型 (GET, POST, PUT, DELETE)
     * @param params           GET/DELETE 请求的查询参数（用于URL查询字符串）
     * @return 响应结果
     */
    public static String sendInternal(String jsonStr, String url, Consumer<Map<String, String>> headerCustomizer, HttpRequestType requestType, Map<String, Object> params, Map<String, File> files) {
        log.info("开始发送" + requestType + "请求，请求参数：" + jsonStr);
        long start = System.currentTimeMillis();

        Map<String, String> headers = new HashMap<>();
        if (headerCustomizer != null) {
            headerCustomizer.accept(headers);
        }

        String value = null;
        try {
            switch (requestType) {
                case POST:
                    value = UnirestClientUtils.postForUnirestString(url, headers, jsonStr);
                    break;
                case POST_FILE:
                    value = UnirestClientUtils.uploadFileWithUnirest(url, headers, files);
                    break;
                case GET:
                    value = UnirestClientUtils.getForString(url, headers, params);
                    break;
                case PUT:
                    value = UnirestClientUtils.putForUnirestString(url, headers, jsonStr);
                    break;
                case DELETE:
                    value = UnirestClientUtils.deleteForString(url, headers, params);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported request type: " + requestType);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        long end = System.currentTimeMillis();
        log.info("请求耗时：" + (end - start) / 1000.0 + "s");
        return value;
    }


    public static String sendInternalByHttpRequestType(String jsonStr, String apiKey, String fastGptApiUrl, Map<String, Object> params, HttpRequestType requestType, Map<String, File> files) {
        return ConnectionUtils.sendInternal(jsonStr, fastGptApiUrl, headers -> headers.put("Authorization", "Bearer " + apiKey), requestType, params, files);
    }
}
